package main

import (
	"encoding/json"
	"fmt"
	"github.com/go-toast/toast"
	"io"
	"net/http"
	"os"
	"path"
	"path/filepath"
)

var key = ""

const url = "https://tsgold.market.alicloudapi.com/shgold"

type Response struct {
	Msg  string `json:"msg"`
	Code uint16 `json:"code"`
	Data struct {
		List []map[string]string `json:"list"`
	} `json:"data"`
}

func main() {
	/// 获取当前工作目录
	cwd, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	configfile := filepath.Join(cwd, "key.conf")
	if file, err := os.Open(configfile); err != nil {
		panic(err)
	} else {
		if body, err := io.ReadAll(file); err != nil {
			panic(err)
		} else {
			key = string(body)
		}
	}
	if icon, err := filepath.Abs(path.Join(cwd, "icon.ico")); err != nil {
		panic(err)
	} else {
		if request, err := http.NewRequest("GET", url, nil); err != nil {
			panic(err)
		} else {
			request.Header.Add(
				"Authorization", fmt.Sprintf("APPCODE %s", key),
			)
			if response, err := (&http.Client{}).Do(request); err != nil {
				panic(err)
			} else {
				if response.StatusCode != http.StatusOK {
					panic(response.StatusCode)
				}
				res := &Response{}
				if err := json.NewDecoder(response.Body).Decode(res); err != nil {
					panic(err)
				} else {
					for _, item := range res.Data.List {
						if item["type"] == "AU99.99" {
							notification := toast.Notification{
								Icon:     icon,
								AppID:    "AU9999",
								Title:    "实时金价",
								Duration: toast.Long,
								Message:  fmt.Sprintf("今日最新金价：%s", item["price"]),
							}
							err := notification.Push()
							if err != nil {
								panic(err)
							}
						}
					}
				}
			}
		}
	}
}
